package com.hunan.api.catv.service.biz.tencent_cloud.cos;

import com.google.gson.JsonObject;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.impl.tencent_cloud.cos.CosService;
import com.hunan.api.catv.utils.FileUtils;
import com.hunan.api.catv.utils.GsonUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

@Service
public class CosBiz extends ResultService {

    @Autowired
    CosService cosService;

    @Autowired
    CacheBiz cacheBiz;

    public ServiceResult upload(Integer fileType, MultipartFile file) {
        JsonObject cosConf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.tencent_cloud_cos_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(cosConf)) {
            String secretId = cosConf.get("secretId").getAsString();
            String secretKey = cosConf.get("secretKey").getAsString();
            String region = cosConf.get("region").getAsString();
            String bucketName = cosConf.get("bucketName").getAsString();
            String domain = cosConf.get("domain").getAsString();
            String fileName = file.getOriginalFilename();
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String newNameFile = System.currentTimeMillis() + "";
            String newFileName = newNameFile + "." + fileSuffix.toLowerCase();
            String currentDay = DateTime.now().toString("yyyyMMdd");
            StringBuilder keyBuilder = new StringBuilder();
            keyBuilder.append(fileType == 1 ? "img/" : "apk/");
            keyBuilder.append(currentDay);
            keyBuilder.append("/");
            keyBuilder.append(newFileName);
            StringBuilder domainPathBuilder = new StringBuilder();
            domainPathBuilder.append(domain);
            domainPathBuilder.append("/");
            domainPathBuilder.append(keyBuilder);
            String domainPath = domainPathBuilder.toString();
            String eTag = cosService.upload(file, secretId, secretKey, region, bucketName, keyBuilder.toString(), fileSuffix);
            if (!ObjectUtils.isEmpty(eTag)) {
                JsonObject result = new JsonObject();
                result.addProperty("size", FileUtils.convertFileSize(file.getSize()));
                result.addProperty("realSize", file.getSize());
                result.addProperty("fileId", eTag);
                result.addProperty("url", domainPath);
                return buildOK(result);
            }
        }
        return buildFail(false, ConstantsMsg.cos_upload_fail);
    }
}
